


import React, { FC, useEffect, useRef,useState } from 'react'
import { Button, Form, Input ,Toast} from 'antd-mobile'
import { Link, useSearchParams,useNavigate} from 'react-router-dom'
import { reg } from '../../utils/validate'
import { Http } from '../../api'
import { connect } from 'react-redux'
import { getuserInfoAsync } from '../../redux/actions'
import MyHead from '../../components/MyHead'
const LoginByPhone: FC<any> = ({
  dispatch
}) => {
  const formRef: any = useRef()
  const [form] = Form.useForm()
  const [disabled,setDisabled] = useState<boolean>(true)
  const [searchParams] = useSearchParams()  // 获取query值
  let [count,setCount] = useState<number>(120)  //防抖
  const [toggle,setToggle] = useState<boolean>(true)  //开关
  let timer:any  = null;  //倒计时
  const router = useNavigate()

  useEffect(()=>{
    const phone =searchParams.get('phone')  //获取里面phone的值
    if (phone) {
      form.setFieldsValue({'phone':phone})
      setDisabled(!reg.phone.test(phone))

    }else{
      form.setFieldsValue({'phone':localStorage.getItem('phone')})
      if(localStorage.getItem('phone')){
        setDisabled(!reg.phone.test(localStorage.getItem('phone')))
      }
    }

    return ()=>{
      clearInterval(timer)
      timer = null
    }
  },[])

    const checkPhone =(value:any)=>{
    console.log(value);
    setDisabled(!reg.phone.test(value))
  }

  const timeDown = ()=>{
    setCount(--count)
    setToggle(false)
    timer = setInterval(()=>{
      if(count>0){
        setCount(--count)
        setToggle(false)
      }else{
        clearInterval(timer)
        timer = null;
        setCount(120)
        setToggle(true)
      }
    },1000)
  }

  
  const startSendCaptcha = async ()=>{
    timeDown()

    let res:any  = await Http.sentcaptcha({
      phone:form.getFieldValue('phone')
    })

    if(res.code==200){
      Toast.show({
        icon:"success",
        content: res.msg,
      })
    }
  }

  // 验证码登录
  const formSubmit = ()=>{
    form.submit()
  }
  const onFinish = async (value: any) => {
    console.log(value)
    let res: any = await Http.verifycaptcha(value)  //验证码接口
    if (res.code == 200) {
      sessionStorage.setItem("token", res.token)  //存 token
      localStorage.setItem("phone", value.phone)
      
      // 验证码通过，修改密码 调接口
      let result :any = await Http.changeuserinfo(value)
      console.log(result);
      router("/login?from=main/mine")
    }
  }


useEffect(()=>{
  console.log(form.getFieldsValue())
},[form.getFieldValue('phone')])



  // 失焦事件
  const checkDbPass=()=>{
    // 失焦时，调取某个字段的正则
    form.validateFields(['dbpass'])  //触发确认的校验
    console.log('12121');
  }


  return (
    <div>
      <MyHead title='找回密码'/>
      <Form 
       onFinish={onFinish}
      form ={form}
      ref={formRef}
      layout='horizontal'
      mode='card'
        footer={
          <div style={{width:'100%',display:'flex'}}>
            <Button style={{flex:1,margin:'0 10px'}} onClick={formSubmit} color='success' size='large'>
              找回密码
            </Button>
            <Button
           style={{flex:1,margin:'0 10px'}}
              color='danger'
              onClick={() => {
                formRef.current.resetFields()
              }}
              size='large'
            >重置数据</Button>
            
          </div>
        }
      >
        <Form.Item label='手机号' name='phone'
          rules={[
            { required: true },
            {pattern:reg.phone,message:"请输入有效的手机号"}
          ]}
        >
          <Input placeholder='请输入用户名' clearable onChange={checkPhone} />
        </Form.Item>
        {/* <Form.Item label='短信验证码' name='captcha' disabled={disabled} extra={
        toggle?<a  onClick={startSendCaptcha}>发送</a>
      :<a>发送</a>}>
          <Input   style={{flex:1}} type="number"  placeholder='请输入验证码' />
        </Form.Item> */}
            <Form.Item label='验证码' name="captcha" extra={
          toggle?<Button color="warning" size='small'   onClick={startSendCaptcha} disabled={disabled} >发送</Button>
          :<Button color="default" size='small'   disabled={disabled} >{count} S</Button>
        }
        rules={[
          { required: true },
          { pattern:reg.code,message:"请输入有效的验证码"}
        ]}
        >
          <Input  style={{flex:1}} type="number"   placeholder='请输入验证码' />
        </Form.Item>

        <Form.Item label='密码' name='password'
         rules={[
          { required: true },
          {pattern:reg.pwd,message:"请输入6-16位的字母和数字组合的密码"}
        ]}
        >
          <Input onBlur={checkDbPass} placeholder='请输入密码' clearable type='password' />
        </Form.Item>

        <Form.Item label='确认密码' name='dbpass'
         rules={[
          { required: true },
          {pattern:reg.pwd,message:"请输入6-16位的字母和数字组合的密码"},
          {
            validator:(rule,value,callback)=>{
            console.log(value);
            console.log(form.getFieldValue('password'));
            if (reg.pwd.test(value) && reg.pwd.test(form.getFieldValue('password'))) {
              // 两次密码的正则通过才去比较是否一致
              // 比较两次密码是否一致
            if (value==form.getFieldValue('password')) {
              return Promise.resolve()  //Promise.resolve方法允许调用时不带参数，直接返回一个resolved状态的 Promise 对象。
            }else{
              return Promise.reject(new Error("两次密码不一样"));
            }
            }else{
              return Promise.resolve()
            }
            
            }
          }
        ]}
        >
          <Input placeholder='请输入确认密码' clearable type='password' />
        </Form.Item>

        <Form.Item>
          <div className="lines" style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
            <div className="item">
            <Link to="/register" style={{color:'pink'}}>去注册?</Link>
            </div>
            <div className="item">
            <Link to="/login" style={{color:'#f50'}}>去登录?</Link>
            </div>
          </div>
        </Form.Item>
      </Form>
    </div>
  )
}

export default connect()(LoginByPhone)